//
//  LyricAnalysis.m
//  歌词解析
//
//  Created by qianfeng on 15/8/15.
//  Copyright (c) 2015年 qianfeng. All rights reserved.
//

#import "LyricAnalysis.h"
#import "Lyric.h"


@implementation LyricAnalysis{
  
    NSMutableArray * _lyricArray;
}

-(id)init{
    if (self = [super init]) {
        _lyricArray = [[NSMutableArray alloc] init];
    }
    return self;
}

-(void)analysisLyricWithPath:(NSString *)path{
    
    NSString * lyricStr = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    NSArray * array = [lyricStr componentsSeparatedByString:@"\n"];
    NSMutableArray * marray = [NSMutableArray arrayWithArray:array];
    
    for (int i = 0; i < marray.count; i++) {
        NSString * lyric = [marray objectAtIndex:i];
        if (lyric.length == 0) {
            [marray removeObjectAtIndex:i];
            i--;
        }
        unichar ch = [lyric characterAtIndex:1];
        if (!isnumber(ch)) {   //删除不是歌词的部分
            [marray removeObjectAtIndex:i];
            i--;
        }
    }
    //把每一行歌词解析成一个个歌词对象
    for (NSString * str in marray) {
        NSArray * strArray = [str componentsSeparatedByString:@"]"];
        for (int i = 0; i < strArray.count - 1; i++) {
            Lyric * eachLyric = [[Lyric alloc]init];
            [eachLyric setLyric:[strArray lastObject]];
            
            NSString * time = [strArray objectAtIndex:i];
            NSDateFormatter * fm = [[NSDateFormatter alloc] init];
            
            [fm setDateFormat:@"[mm:ss.s]"];
            
            NSDate * date1 = [fm dateFromString:time];
            NSDate * date2 = [fm dateFromString:@"[00:00.0]"];
            
            NSTimeInterval timeinterval1 = [date1 timeIntervalSince1970];
            NSTimeInterval timeinterval2 = [date2 timeIntervalSince1970];
            
            [eachLyric setTime:timeinterval1 - timeinterval2];
            
            [_lyricArray addObject:eachLyric];
            
        }
    }
    for (int i = 0;  i < _lyricArray.count - 1; i++) {
        for (int j = i + 1; j < _lyricArray.count; j++) {
            Lyric * Lyric_i = [_lyricArray objectAtIndex:i];
            Lyric * Lyric_j = [_lyricArray objectAtIndex:j];
            if ([Lyric_i getTime] > [Lyric_j getTime]) {
                [_lyricArray exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
    }
    
}

- (NSString *)showLyricWithTime:(NSTimeInterval)time{

    for (int i = (int) [_lyricArray count] - 1; i >= 0; i--) {
        Lyric * lyric = [_lyricArray objectAtIndex:i];
        if (time > [[_lyricArray lastObject] getTime]) {
            exit(0);
        }
        if ([lyric getTime] < time) {
            return [lyric getLyric];
        }
    }
    
    
    return @"........";
}

@end
